<?php

namespace App\Services;

use App\Common\SDK\Facade\FenZhangTong;
use App\Models\FinanceSupplier;
use Illuminate\Http\Request;
use Symfony\Component\HttpKernel\Exception\HttpException;

class SupplierService
{
    public function store(Request $request)
    {
        $reqData = validator($request->all(), [
            'name' => 'required',
            'birthday' => 'nullable|date',
            'gender' => 'in:' . implode(',', [FinanceSupplier::GENDER_MALE, FinanceSupplier::GENDER_FAMALE]),
            'email' => 'email',
            'id_type' => 'required|in:' . implode(',', [FinanceSupplier::ID_TYPE_MAINLAND, FinanceSupplier::ID_TYPE_HONG_KONG_AND_MACAU, FinanceSupplier::ID_TYPE_TAIWAN]),
            'id_no' => 'required',

            'legal_expire_date' => 'required_if:id_type,A|date',
            'legal_auth_date' => 'required_if:id_type,A|date',
            'occupation' => 'required_if:id_type,A|in:0001,0002,0003,0004,0005,0006,0007,0008,0009,0010',
            'address' => 'required_if:id_type,A',
            'legal_address' => 'required_if:id_type,A',
            'issue_office' => 'required_if:id_type,A',

            'bank' => 'required|in:' . implode(',', array_keys(FinanceSupplier::GUO_JI_YIN_HANG_MAP)),
            'bank_card_no' => 'required',
            'phone' => ['required', 'regex:/^(?:\+?86)?1(?:3\d{3}|5[^4\D]\d{2}|8\d{3}|7(?:[235-8]\d{2}|4(?:0\d|1[0-2]|9\d))|9[0-35-9]\d{2}|66\d{2})\d{6}$/'],
        ], [
            'name.required' => '姓名为必填项',
            'birthday.date' => '生日格式错误',
            'gender.in' => '性别不合法',
            'email.email' => '邮箱地址不合法',
            'id_type.required' => '证件类型不得为空',
            'id_type.in' => '证件类型不合法',
            'id_no.required' => '证件号码为必填项',
            'legal_expire_date.required_if' => '证件有效期为必填项',
            'legal_auth_date.required_if' => '证件起始日期为必填项',
            'occupation.required_if' => '职业为必填项',
            'occupation.in' => '职业不合法',
            'address.required_if' => '联系地址为必填项',
            'legal_address.required_if' => '证件地址为必填项',
            'issue_office.required_if' => '发证机关为必填项',
            'bank.required' => '银行为必选项',
            'bank.in' => '银行不合法',
            'bank_card_no.required' => '银行卡号为必填项',
            'phone.required' => '预留手机号为必填项',
            'phone.regex' => '预留手机号填写不正确',
        ])->validate();

        $supplier = null;
        try {
            \DB::beginTransaction();

            $transId = substr(app('Barryvdh\Debugbar\LaravelDebugbar')->getRequestIdGenerator()->generate(), 1);
            $reqData['trans_id'] = $transId;
            $supplier = FinanceSupplier::query()->create($reqData);

            $fztReq = [
                'transId' => $transId, // 这里单独传 transId 后面回调要用这个来查
                'custName' => $reqData['name'],
                'gender' => $reqData['gender'] ?? FinanceSupplier::GENDER_MALE,
                'birthDay' => $reqData['birthday'] ?? '',
                'idType' => $reqData['id_type'],
                'idNo' => $reqData['id_no'],
                'mobileNo' => $reqData['phone'],
                'email' => $reqData['email'] ?? '',
                'openBank' => $reqData['bank'],
                'cardNo' => $reqData['bank_card_no'],
                'legalExpireDate' => $reqData['legal_expire_date'] ?? '',
                'legalAuthDate' => $reqData['legal_auth_date'] ?? '',
                'occupation' => $reqData['occupation'] ?? '',
                'address' => $reqData['address'] ?? '',
                'legalAddress' => $reqData['legal_address'] ?? '',
                'issueOffice' => $reqData['issue_office'] ?? '',
                'notifyUrl' => url('/api/finance/notify/suppliers'),
                'returnUrl' => url('finance/supplier/supplier-list'),
            ];
            $fztSupplier = FenZhangTong::individualCustomerRegistrationApplication(array_filter($fztReq, fn($item) => !empty($item)));
            $supplier->update(['plat_cust_no' => $fztSupplier['platCustNo'] ?? '', 'ret_url' => base64_encode($fztSupplier['retUrl'])]);

            \DB::commit();
        } catch (\Exception $e) {
            \DB::rollBack();
            \Log::error($e);
            throw new HttpException(400, $e->getMessage());
        }

        return $fztSupplier;
    }
}
